#include "AvgFunctionNode.h"
#include "..\Common\AssertHelper.h"

using namespace std;

namespace CExpression
{
	void AvgFunctionNode::Eval(ExecuteContext &context)
	{
		double sum=0;
		double count=0;
		for(vector< shared_ptr<Node> >::iterator i=this->parameters.begin();i!=this->parameters.end();++i)
		{
			(*i)->Eval(context);
			if(AssertHelper::ExpectType(context.TempResultType(),ExecuteRunTimeType::Double,context,TEXT("Avg function parameter must be double type.")))
			{
				sum+=context.GlobalTempNum();
				++count;
			}
			else
			{
				break;
			}
		}
		if(!context.ErrorOccured())
		{
			context.SetGlobalTempNum(sum/count);
			context.SetTempResultType(ExecuteRunTimeType::Double);
		}
	}

	shared_ptr<Node> AvgFunctionNode::Clone(Expression &parent)
	{
		shared_ptr<Node> result(new AvgFunctionNode());
		AvgFunctionNode *ptr=static_cast<AvgFunctionNode*>(result.get());
		for(vector< shared_ptr<Node> >::iterator i=this->parameters.begin();i!=this->parameters.end();++i)
		{
			ptr->AddParameter((*i)->Clone(parent));
		}
		return result;
	}
}